package com.kakahair.plat.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.kakahair.common.controller.BaseController;
import com.kakahair.common.util.AjaxResponse;
import com.kakahair.common.util.SessionUtil;
import com.kakahair.common.util.Utility;
import com.kakahair.plat.entity.Bservice;
import com.kakahair.plat.entity.Shop;
import com.kakahair.plat.entity.Technician;
import com.kakahair.plat.entity.DTO.ShopDTO;
import com.kakahair.plat.service.BserviceService;
import com.kakahair.plat.service.ShopService;
import com.kakahair.plat.service.TechnicianService;

import net.sf.json.JSONObject;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Tiddar
 * @since 2018-04-07
 */
@Controller
@RequestMapping("/shop")
public class ShopController extends BaseController {
	@Autowired
	ShopService shopService;
	@Autowired
	TechnicianService technicianService;
	@Autowired
	BserviceService bserviceService;

	private String uploadPath;

	public String getUploadPath() {
		return uploadPath;
	}

	public void setUploadPath(String uploadPath) {
		this.uploadPath = uploadPath;
	}

	/**
	 * 
	 * @author TiddAr @Title: list @Description:查询商铺列表 @param @param
	 *         cityName @param @param areaName @param @param sortType @param @param
	 *         currentPage @param @param pageSize @param @return 参数 @return
	 *         AjaxResponse 返回类型 @date 2018年4月26日
	 */
	@ResponseBody
	@PostMapping("/list")
	public AjaxResponse list(@RequestBody JSONObject listCondition) {
		String cityName = listCondition.optString("cityName");
		String areaName = listCondition.optString("areaName");
		Integer sortType = listCondition.optInt("sortType", 1);
		Integer currentPage = listCondition.optInt("currentPage", 1);
		Integer pageSize = listCondition.optInt("pageSize", 6);
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			System.out.println("cityName:" + cityName);
			ajaxResponse.setData(shopService.list(cityName, areaName, sortType, currentPage, pageSize));
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setMessage(e.toString());
			ajaxResponse.setSuccess(false);
		}
		return ajaxResponse;
	}

	/**
	 * 
	 * @author TiddAr @Title: queryWords @Description:通过关键词搜索概要 @param @return
	 *         参数 @return AjaxResponse 返回类型 @date 2018年4月22日
	 */
	@ResponseBody
	@GetMapping("/query")
	public AjaxResponse query(String title) {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			List<Shop> shops = shopService.selectList(new EntityWrapper<Shop>().like("title", title));
			ajaxResponse.setData(shops);
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			ajaxResponse.setMessage(e.toString());
			ajaxResponse.setSuccess(false);
		}

		return ajaxResponse;
	}

	@ResponseBody
	@GetMapping("/detail/{shopId}")
	public AjaxResponse detail(@PathVariable Integer shopId) {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			Shop shop = shopService.detail(shopId);
			if (null == shop) {
				ajaxResponse.setSuccess(false);
				ajaxResponse.setMessage("查询商铺条数为0");
			}
			ajaxResponse.setData(shop);
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setMessage(e.toString());
			ajaxResponse.setSuccess(false);
		}
		return ajaxResponse;
	}

	@ResponseBody
	@GetMapping("/me")
	public AjaxResponse me() {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			String userId = SessionUtil.getLoginUser(request).getOpenid();
			Shop shop = shopService.me(userId);
			if (null == shop) {
				ajaxResponse.setSuccess(false);
				ajaxResponse.setMessage("查询商铺条数为0");
			}
			ajaxResponse.setData(shop);
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setMessage(e.toString());
			ajaxResponse.setSuccess(false);
		}
		return ajaxResponse;
	}

	@ResponseBody
	@GetMapping("/count")
	public AjaxResponse count(Integer shopId) {
		AjaxResponse ajaxResponse = AjaxResponse.instance();
		try {
			ajaxResponse.setData(shopService.count(shopId));
			ajaxResponse.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxResponse.setMessage(e.toString());
			ajaxResponse.setSuccess(false);
		}
		return ajaxResponse;
	}

	@ResponseBody
	@PostMapping("/insert")
	public ShopDTO submit(ShopDTO shopdto, @RequestParam(value = "shopImg") MultipartFile shopImg,
			@RequestParam(value = "shopAva") MultipartFile shopAva,
			@RequestParam(value = "techPic") MultipartFile[] techPics) {
		Shop shop = shopdto.getShop();
		List<Technician> techs = shopdto.getTechnician();
		List<Bservice> bservices = shopdto.getBservice();
		// 如果目录不存在，创建一个目录
		if (!new File(uploadPath + "detail\\").exists()) {
			File dir = new File(uploadPath + "detail\\");
			dir.mkdirs();
		}
		if (!new File(uploadPath + "store\\").exists()) {
			File dir = new File(uploadPath + "store\\");
			dir.mkdirs();
		}
		if (!new File(uploadPath + "technicians\\").exists()) {
			File dir = new File(uploadPath + "technicians\\");
			dir.mkdirs();
		}
		try {
			String fileName = shopImg.getOriginalFilename();
			System.out.println("原始文件名:" + fileName);
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
			// 新文件名
			fileName = Utility.getUUID() + "." + fileType;

			String path = uploadPath + "detail\\" + fileName;
			File localFile = new File(path);

			shopImg.transferTo(localFile);
			shop.setImage(fileName);
			fileName = shopAva.getOriginalFilename();
			System.out.println("原始文件名:" + fileName);
			fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
			// 新文件名
			fileName = Utility.getUUID() + "." + fileType;
			path = uploadPath + "store\\" + fileName;
			localFile = new File(path);

			shopAva.transferTo(localFile);
			logger.debug("上传图片成功!");
			shop.setAvatar(fileName);
			int index = 0;
			for (MultipartFile techPic : techPics) {
				if (techPic.isEmpty())
					continue;
				fileName = techPic.getOriginalFilename();
				System.out.println("原始文件名:" + fileName);
				fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
				// 新文件名
				fileName = Utility.getUUID() + "." + fileType;
				path = uploadPath + "technicians\\" + fileName;
				localFile = new File(path);

				techPic.transferTo(localFile);
				logger.debug("上传图片成功!");
				shopdto.getTechnician().get(index).setPic(fileName);
				index++;

			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		shop.setCity("保定市").setStar(BigDecimal.valueOf(5));
		shopService.insert(shop);
		Integer shopId = Integer.valueOf(shopService
				.selectObj(new EntityWrapper<Shop>().setSqlSelect("id").where("image = {0}", shop.getImage()))
				.toString());
		techs.forEach(tech -> {
			tech.setShopId(shopId);
			technicianService.insert(tech);
			Integer technicianId = Integer.valueOf(technicianService
					.selectObj(new EntityWrapper<Technician>().setSqlSelect("id").where("pic = {0}", tech.getPic()))
					.toString());
			bservices.forEach(bservice -> {

				if (!("护理 染发 烫发").contains(bservice.getName())) {
					bserviceService.insert(bservice.setUuid(Utility.getUUID()).setTechId(technicianId));
				} else {
					bservice.setMoreChoice(true);
					bserviceService.insert(bservice.setUuid(Utility.getUUID()).setTechId(technicianId));
					bservice.getMoreService().forEach(moreservice -> {
						Integer parentId = Integer.valueOf(bserviceService.selectObj(new EntityWrapper<Bservice>()
								.setSqlSelect("id").where("uuid = {0}", bservice.getUuid())).toString());
						moreservice.setParentId(parentId);
						bserviceService.insert(moreservice.setTechId(technicianId));
					});
				}
			});
		});
		return shopdto;
	}

}
